<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {CircleStencil, Cropper} from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import {handleError, success, warning} from '@/utils/message'
import {validate} from '@/utils/validate'
import {MESSAGES, USER} from '@/constants/messages'
import {EyeOutlined, FolderOutlined, LockOutlined, PictureOutlined, UploadOutlined} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import MainLayout from '@/components/layout/MainLayout.vue'
import ProgressiveImage from '@/components/common/ProgressiveImage.vue'
import {useAuthStore} from '@/stores/modules/auth'
import {fileApi, pictureApi, spaceApi, userApi} from '@/api'
import type {PictureVO} from '@/types/vo/picture'
import {useCropper} from '@/composables/useCropper'

const authStore = useAuthStore()

const updating = ref(false)
const resetting = ref(false)
const editModalVisible = ref(false)
const passwordModalVisible = ref(false)

// 使用裁剪组合式函数 - 圆形头像
const {
  cropperModalVisible,
  cropperImageSrc,
  cropperRef,
  previewUrl: avatarPreview,
  croppedFile: avatarFile,
  handleFileSelect: handleAvatarChange,
  zoom,
  rotate,
  flip,
  reset,
  confirm: handleCropperConfirm,
  cancel: handleCropperCancel
} = useCropper({
  maxSize: 2,
  aspectRatio: 1,
  shape: 'circle',
  outputFormat: 'image/jpeg'
})

const myPictures = ref<PictureVO[]>([])
const stats = reactive({
  pictureCount: 0,
  spaceCount: 0,
  totalViews: 0
})

const editForm = reactive({
  userName: '',
  userAvatar: '',
  userProfile: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载我的图片
const loadMyPictures = async () => {
  try {
    const result = await pictureApi.list({
      current: 1,
      size: 8,
      userId: authStore.user?.id
    })
    myPictures.value = result.records
    stats.pictureCount = result.total
    stats.totalViews = result.records.reduce((sum, p) => sum + (p.viewCount || 0), 0)
  } catch (error: any) {
    // 静默失败，不影响主流程
  }
}

// 加载我的空间
const loadMySpaces = async () => {
  try {
    const result = await spaceApi.getMySpaces()
    stats.spaceCount = result.owner.length
  } catch (error: any) {
    // 静默失败，不影响主流程
  }
}

// 显示编辑对话框
const showEditModal = () => {
  editForm.userName = authStore.user?.userName || ''
  editForm.userAvatar = authStore.user?.userAvatar || ''
  editForm.userProfile = authStore.user?.userProfile || ''
  avatarPreview.value = ''
  avatarFile.value = null
  editModalVisible.value = true
}

// 更新资料
const handleUpdateProfile = async () => {
  updating.value = true
  try {
    let avatarUrl = editForm.userAvatar

    // 如果有新头像，先上传到专用接口
    if (avatarFile.value) {
      avatarUrl = await fileApi.uploadAvatar(avatarFile.value)
    }

    // 更新用户资料
    await userApi.updateProfile({
      userName: editForm.userName,
      userAvatar: avatarUrl,
      userProfile: editForm.userProfile
    })

    await authStore.fetchCurrentUser()
    editModalVisible.value = false
    success(USER.PROFILE_UPDATE_SUCCESS)
  } catch (error: any) {
    handleError(error, MESSAGES.UPDATE_FAILED)
  } finally {
    updating.value = false
  }
}

// 显示修改密码对话框
const showPasswordModal = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordModalVisible.value = true
}

// 修改密码
const handleResetPassword = async () => {
  if (!validate.required(passwordForm.oldPassword) ||
      !validate.required(passwordForm.newPassword) ||
      !validate.required(passwordForm.confirmPassword)) {
    warning('请填写完整信息')
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    warning(USER.PASSWORD_MISMATCH)
    return
  }

  if (!validate.password(passwordForm.newPassword)) {
    warning('密码长度应为6-20个字符')
    return
  }

  resetting.value = true
  try {
    await userApi.resetPassword(passwordForm)
    passwordModalVisible.value = false
    success(USER.PASSWORD_RESET_SUCCESS)

    // 退出登录
    setTimeout(async () => {
      await authStore.logout()
      window.location.href = '/login'
    }, 1500)
  } catch (error: any) {
    handleError(error, USER.PROFILE_UPDATE_FAILED)
  } finally {
    resetting.value = false
  }
}

// 格式化日期
const formatDate = (date?: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

onMounted(() => {
  loadMyPictures()
  loadMySpaces()
})
</script>

<template>
  <main-layout>
    <div class="profile-container">
      <a-row :gutter="24">
        <!-- 左侧个人信息 -->
        <a-col :md="8" :xs="24">
          <a-card title="个人信息">
            <div class="user-avatar">
              <a-avatar :size="120" :src="authStore.user?.userAvatar">
                {{ authStore.user?.userName?.charAt(0) || 'U' }}
              </a-avatar>
              <a-button size="small" type="link" @click="showEditModal">编辑资料</a-button>
            </div>

            <a-descriptions :column="1" style="margin-top: 24px">
              <a-descriptions-item label="账号">
                {{ authStore.user?.userAccount }}
              </a-descriptions-item>
              <a-descriptions-item label="昵称">
                {{ authStore.user?.userName || '未设置' }}
              </a-descriptions-item>
              <a-descriptions-item label="邮箱">
                {{ authStore.user?.email || '未绑定' }}
              </a-descriptions-item>
              <a-descriptions-item label="个人简介">
                {{ authStore.user?.userProfile || '这个人很懒，什么都没写' }}
              </a-descriptions-item>
              <a-descriptions-item label="注册时间">
                {{ formatDate(authStore.user?.createTime) }}
              </a-descriptions-item>
            </a-descriptions>

            <a-divider/>

            <a-space direction="vertical" style="width: 100%">
              <a-button block @click="showPasswordModal">
                <template #icon>
                  <LockOutlined/>
                </template>
                修改密码
              </a-button>
            </a-space>
          </a-card>
        </a-col>

        <!-- 右侧统计信息 -->
        <a-col :md="16" :xs="24">
          <a-card title="我的统计">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic
                    :value="stats.pictureCount"
                    suffix="张"
                    title="上传图片"
                >
                  <template #prefix>
                    <PictureOutlined/>
                  </template>
                </a-statistic>
              </a-col>
              <a-col :span="8">
                <a-statistic
                    :value="stats.spaceCount"
                    suffix="个"
                    title="创建空间"
                >
                  <template #prefix>
                    <FolderOutlined/>
                  </template>
                </a-statistic>
              </a-col>
              <a-col :span="8">
                <a-statistic
                    :value="stats.totalViews"
                    suffix="次"
                    title="总浏览量"
                >
                  <template #prefix>
                    <EyeOutlined/>
                  </template>
                </a-statistic>
              </a-col>
            </a-row>
          </a-card>

          <a-card style="margin-top: 24px" title="我的图片">
            <div v-if="myPictures.length > 0" class="pictures-grid">
              <div
                  v-for="picture in myPictures"
                  :key="picture.id"
                  class="picture-item"
                  @click="$router.push(`/picture/${picture.id}`)"
              >
                <progressive-image :alt="picture.pictureName" :lazy="true"
                                   :src="picture.thumbnailUrl || picture.fileUrl"/>
              </div>
            </div>
            <a-empty v-else description="还没有上传图片"/>
          </a-card>
        </a-col>
      </a-row>

      <!-- 编辑资料对话框 -->
      <a-modal
          v-model:open="editModalVisible"
          :confirm-loading="updating"
          title="编辑资料"
          @ok="handleUpdateProfile"
      >
        <a-form layout="vertical">
          <a-form-item label="昵称">
            <a-input v-model:value="editForm.userName" :maxlength="20" placeholder="请输入昵称"/>
          </a-form-item>

          <a-form-item label="头像">
            <div class="avatar-upload">
              <div class="avatar-preview">
                <a-avatar :size="100" :src="avatarPreview || editForm.userAvatar">
                  {{ editForm.userName?.charAt(0) || 'U' }}
                </a-avatar>
              </div>
              <a-upload
                  :before-upload="handleAvatarChange"
                  :show-upload-list="false"
                  accept="image/*"
              >
                <a-button block>
                  <UploadOutlined/>
                  {{ avatarPreview ? '重新选择' : '选择头像' }}
                </a-button>
              </a-upload>
              <p class="upload-hint">支持 JPG、PNG、GIF，不超过 2MB</p>
            </div>
          </a-form-item>

          <a-form-item label="个人简介">
            <a-textarea v-model:value="editForm.userProfile" :maxlength="200" :rows="4" placeholder="介绍一下自己吧"/>
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 修改密码对话框 -->
      <a-modal
          v-model:open="passwordModalVisible"
          :confirm-loading="resetting"
          title="修改密码"
          @ok="handleResetPassword"
      >
        <a-form layout="vertical">
          <a-form-item label="旧密码" required>
            <a-input-password v-model:value="passwordForm.oldPassword"/>
          </a-form-item>
          <a-form-item label="新密码" required>
            <a-input-password v-model:value="passwordForm.newPassword"/>
          </a-form-item>
          <a-form-item label="确认新密码" required>
            <a-input-password v-model:value="passwordForm.confirmPassword"/>
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 头像裁剪对话框 -->
      <a-modal
          v-model:open="cropperModalVisible"
          :width="700"
          cancel-text="取消"
          ok-text="确认"
          title="调整头像"
          @cancel="handleCropperCancel"
          @ok="handleCropperConfirm"
      >
        <div class="cropper-container">
          <cropper
              ref="cropperRef"
              :src="cropperImageSrc"
              :stencil-component="CircleStencil"
              class="cropper"
          />
          <div class="cropper-toolbar">
            <a-space :size="12">
              <a-button size="small" @click="zoom(1.1)">放大</a-button>
              <a-button size="small" @click="zoom(0.9)">缩小</a-button>
              <a-button size="small" @click="rotate(90)">旋转</a-button>
              <a-button size="small" @click="flip(true, false)">翻转</a-button>
              <a-button size="small" @click="reset">重置</a-button>
            </a-space>
          </div>
          <p class="cropper-hint">💡 拖动调整位置，滚轮缩放大小</p>
        </div>
      </a-modal>
    </div>
  </main-layout>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;
@use '@/assets/styles/components.scss' as *;

.profile-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: $spacing-xl;

  @include responsive($breakpoint-md) {
    padding: $spacing-lg;
  }
}

.user-avatar {
  text-align: center;

  .ant-avatar {
    margin-bottom: $spacing-md;
    border: 3px solid $border-light;
    box-shadow: $shadow-md;
  }
}

.pictures-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: $spacing-md;
}

.picture-item {
  cursor: pointer;
  border-radius: $radius-md;
  overflow: hidden;
  background: $gradient-bg;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 150px;
  transition: $transition-all;

  &:hover {
    transform: translateY(-4px);
    box-shadow: $shadow-card-hover;

    :deep(.progressive-image img) {
      transform: scale(1.1);
    }
  }

  :deep(.progressive-image) {
    width: 100%;
    border-radius: 0;

    img {
      transition: $transition-transform;
    }
  }
}

.avatar-upload {
  @include avatar-upload;
}

.cropper-container {
  @include cropper-container;
}
</style>